package com.garlic.face.jlf.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.garlic.face.jlf.App;
import com.garlic.face.jlf.R;
import com.garlic.face.jlf.base.BaseActivity;
import com.garlic.face.jlf.presenter.BarCodeContract;
import com.garlic.face.jlf.presenter.BarCodePresenter;
import com.garlic.face.jlf.transaction.Means;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.ToastUtils;
import com.garlic.face.jlf.utils.Tools;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

/**
 * @author wenhui02.liu
 * @date 2018/8/9.
 */

public class BarCodePayActivity extends BaseActivity implements BarCodeContract.View {

    private String TAG = "BarCodePayActivity";

    private ImageView mShopBrand;
    TextView mCancel;
    private CountDownTimer mCountDownTimer;
    String mPayBarCode = "";

    BarCodeContract.Presenter mPresenter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.paying_activity);
        mPresenter = new BarCodePresenter(this);

        EventBus.getDefault().register(this);
        mCancel = (TextView) findViewById(R.id.cancel_pay);
        mCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                View root = View.inflate(BarCodePayActivity.this, R.layout.close_dialog, null);
                AlertDialog.Builder builder = new AlertDialog.Builder(BarCodePayActivity.this).setView
                        (root).setCancelable(false);
                final Dialog dialog = builder.create();
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                root.findViewById(R.id.goto_agin).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                root.findViewById(R.id.cancel_action).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        showProgress();
                        mPresenter.cancelPay("条码支付页面取消交易[手动]");
                    }
                });
            }
        });

        mCountDownTimer = new CountDownTimer(120 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                String s = String.format(getResources().getString(R.string.countdown_cancelPay), (int)millisUntilFinished / 1000);
                mCancel.setText(s);
            }

            @Override
            public void onFinish() {
                mPresenter.cancelPay("条码支付页面取消交易[自动]");
            }
        }.start();

        TextView amount = (TextView) findViewById(R.id.amount);
        double price = Means.getInstance().getRec_Tran().getAmount() - Means.getInstance().getRec_Tran().getPay_amt();
        amount.setText(String.format(getResources().getString(R.string.money_format), Tools.getFormatNumber(price)));

        mShopBrand = (ImageView) findViewById(R.id.title_img);
        mShopBrand.setImageDrawable(this.getResources().getDrawable(R.mipmap.jlf_logo));
        App.playSound(getResources().getString(R.string.sound_start_alipay_scan));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destoryTimer();
        EventBus.getDefault().unregister(this);
        mPresenter.destoryMXdevice();
    }

    @Override
    public void destoryTimer() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    @Override
    public void toSuccssActivity(String result) {
        App.clearToMainActivity();
        Intent intent = new Intent(BarCodePayActivity.this, PaySuccessActivity.class);
        intent.putExtra("scene", "barpay");
        startActivity(intent);
    }

    @Override
    public void toFailureActivity(String msg, String actionType) {
        Intent intent = new Intent(BarCodePayActivity.this, PayFailActivity.class);
        intent.putExtra("error_message", msg);
        intent.putExtra("action_type", actionType);
        startActivity(intent);
        finish();
    }


    @Override
    public void gotoMain() {
        App.clearToMainActivity();
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            LogUtils.d("getAction=" + String.valueOf(event.getAction())
                    + ";getKeyCode=" + String.valueOf(event.getKeyCode())
                    + ";getCharacters=" + event.getCharacters()
                    + ";getScanCode=" + event.getScanCode()
                    + ";getUnicodeChar=" + event.getUnicodeChar()
                    + ";getNumber=" + event.getNumber(), false);
            if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                LogUtils.d("dispatchKeyEvent: KEYCODE_ENTER:", false);
                LogUtils.d("Main=" + mPayBarCode, false);
                if(TextUtils.isEmpty(mPayBarCode) || mPayBarCode.length() < 18){
                    ToastUtils.toastShow("请重新扫码支付宝付款码", ToastUtils.ERROR);
                    mPayBarCode = "";
                }else {
                    String code = mPayBarCode.substring(1, mPayBarCode.length());
                    if (!(code.startsWith("25") || code.startsWith("26")
                            || code.startsWith("27") || code.startsWith("28")
                            || code.startsWith("29") || code.startsWith("30"))) {
                        ToastUtils.toastShow("请使用支付宝付款码", ToastUtils.ERROR);
                        mPayBarCode = "";
                    } else {
                        mPresenter.payBarCode(mPayBarCode);
                        mPayBarCode = "";
                    }
                }
            } else if (event.getUnicodeChar() == 0) {
            } else if ((char) event.getUnicodeChar() == '#') {
                if(TextUtils.isEmpty(mPayBarCode) || mPayBarCode.length() < 18){
                    ToastUtils.toastShow("请重新扫码支付宝付款码", ToastUtils.ERROR);
                    mPayBarCode = "";
                }else {
                    if (mPayBarCode.startsWith("null")) {
                        mPayBarCode = mPayBarCode.replace("null", "");
                    }
                    LogUtils.d("扫描到付款码，发起支付" + mPayBarCode, true);
                    String code = mPayBarCode.substring(1, mPayBarCode.length());
                    if (!(code.startsWith("25") || code.startsWith("26")
                            || code.startsWith("27") || code.startsWith("28")
                            || code.startsWith("29") || code.startsWith("30"))) {
                        ToastUtils.toastShow("请使用支付宝付款码", ToastUtils.ERROR);
                        mPayBarCode = "";
                    } else {
                        mPresenter.payBarCode(mPayBarCode);
                        mPayBarCode = "";
                    }
                }
            } else {
                mPayBarCode += (char) event.getUnicodeChar();
                LogUtils.d("Main=" + mPayBarCode.toString(), false);
            }
        }


        return super.dispatchKeyEvent(event);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveResponse(JSONObject jsonObject) {
        LogUtils.d("支付返回,收到service消息" + jsonObject.toString(), true);
        mPresenter.parseJson(jsonObject);
    }


}
